package com.masterclient.app.modules.aftersale;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.GridLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.eoner.baselibrary.bean.aftersale.CommentProductBean;
import com.eoner.baselibrary.bean.personal.UploadImgBean;
import com.eoner.common.config.Config;
import com.eoner.baselib.utils.notify.RxBus;
import com.eoner.managerlibrary.sobot.SobotManager;
import com.masterclient.app.App;
import com.masterclient.app.BaseActivity;
import com.masterclient.app.R;
import com.masterclient.app.modules.aftersale.adapter.CommentAdapter;
import com.masterclient.app.modules.aftersale.contract.CommentContract;
import com.masterclient.app.modules.aftersale.contract.CommentPresenter;
import com.eoner.uikit.dialog.simple.ChooseHeadImgDialog;
import com.gyf.immersionbar.ImmersionBar;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.sobot.chat.SobotApi;
import com.sobot.chat.api.enumtype.SobotChatTitleDisplayMode;
import com.sobot.chat.api.model.Information;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import top.zibin.luban.Luban;

import static com.masterclient.app.businessmodule.usermodule.userinfo.UserInfoActivity.IMAGE_PICKER;
import static com.masterclient.app.businessmodule.usermodule.userinfo.UserInfoActivity.REQUEST_CODE_SELECT;

/**
 * 作者：sean
 * 创建时间：2017/8/1 15:47
 * 功能说明：
 */

public class CommentActivity extends BaseActivity<CommentPresenter> implements CommentContract.View{

    @BindView(R.id.rl_back)
    RelativeLayout rlBack;
    @BindView(R.id.rl_message)
    RelativeLayout rlMessage;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.iv_unread)
    ImageView ivUnread;
    @BindView(R.id.tv_logist)
    TextView tvLogist;
//    @BindView(R.id.tv_kefu)
//    TextView tvKefu;
    @BindView(R.id.et_handle)
    EditText etHandle;

    private CommentAdapter adapter;
    private ChooseHeadImgDialog headImgDialog;
    private int mPosition = -1;

    private static final int IMAGE_SIZE = 4;

    String order_id;
    public List<CommentProductBean.DataBean.ShProductsBean> productList;
    private RxBus rxBus;
    private RxPermissions rxPermissions;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_comment);
        ButterKnife.bind(this);
        rxBus = RxBus.$();
        ImmersionBar.with(this).barColor(R.color.black).fitsSystemWindows(true).keyboardEnable(false).keyboardMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE).init();
        rxPermissions = new RxPermissions(this);

//        tvKefu.setTypeface(iconfont);
        order_id = getBundleString("order_id");
        adapter = new CommentAdapter();
        recyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        recyclerView.setAdapter(adapter);

        adapter.bindToRecyclerView(recyclerView);
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setMultiMode(true);
        imagePicker.setSelectLimit(IMAGE_SIZE);


        adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()) {
                    case R.id.rl_add_img:
                        mPosition = position;
                        if (productList.get(position).getImages() == null) {
                            imagePicker.setSelectLimit(IMAGE_SIZE);
                        } else {
                            imagePicker.setSelectLimit(IMAGE_SIZE - productList.get(position).getImages().size());
                        }
                        headImgDialog.show();
                        break;
                }
            }
        });


        headImgDialog = new ChooseHeadImgDialog(mContext, "图片上传", "相册", "拍照");
        headImgDialog.setOnChooseListener(new ChooseHeadImgDialog.OnChooseListener() {
            @Override
            public void album() {
                Intent intent = new Intent(mContext, ImageGridActivity.class);
                startActivityForResult(intent, IMAGE_PICKER);
            }

            @SuppressLint("CheckResult")
            @Override
            public void photo() {
                rxPermissions
                        .requestEach(Manifest.permission.CAMERA)
                        .subscribe(permission -> { // will emit 2 Permission objects
                            if (permission.granted) {
                                // `permission.name` is granted !
                                Intent intent = new Intent(mContext, ImageGridActivity.class);
                                intent.putExtra(ImageGridActivity.EXTRAS_TAKE_PICKERS, true); // 是否是直接打开相机
                                startActivityForResult(intent, REQUEST_CODE_SELECT);
                            } else if (permission.shouldShowRequestPermissionRationale) {
                                // Denied permission without ask never again
                            } else {
                                // Denied permission with ask never again
                                // Need to go to the settings
                            }
                        });
            }
        });
        mPresenter.getCommentProduct(order_id);


        rxBus.OnEvent(rxBus.register(Config.MSG_UNREAD), new Consumer<Object>() {
            @Override
            public void accept(@NonNull Object o) throws Exception {
                if (Config.UNREAD > 0) {
                    ivUnread.setVisibility(View.VISIBLE);
                } else {
                    ivUnread.setVisibility(View.INVISIBLE);
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        rxBus.unregister(Config.MSG_UNREAD);
        super.onDestroy();
    }

    @Override
    protected void onPause() {
        hideSoftInput(etHandle);
        super.onPause();
    }

    @OnClick({R.id.rl_back, R.id.tv_logist, R.id.rl_message})
    void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_back:
                finish();
                break;
            case R.id.tv_logist:
                tvLogist.setClickable(false);
                Map<String, String> content = new HashMap<>();
                Map<String, String> rating = new HashMap<>();
                Map<String, List<String>> image = new HashMap<>();
                if (productList == null) return;
                for (CommentProductBean.DataBean.ShProductsBean productsBean : productList) {

                    if (!TextUtils.isEmpty(productsBean.getComment())) {
                        content.put(productsBean.getSh_order_product_id(), productsBean.getComment());
                    }
                    if (!TextUtils.isEmpty(productsBean.getCheckLevel())) {
                        rating.put(productsBean.getSh_order_product_id(), productsBean.getCheckLevel());
                    }

                    if (productsBean.getImages() != null) {
                        List<UploadImgBean.DataBean> list = productsBean.getImages();

                        List<String> imageStrs = new ArrayList<>();

                        for (UploadImgBean.DataBean dataBean : list) {
                            imageStrs.add(dataBean.getSh_image_url());
                        }
                        image.put(productsBean.getSh_order_product_id(), imageStrs);
                    }
                }

                if (content.size() == 0) {
                    showToast("您还未输入你的使用心得");
                    tvLogist.setClickable(true);
                    return;
                }

                if (rating.size() == 0) {
                    showToast("请为一个商品打分");
                    tvLogist.setClickable(true);
                    return;
                }
                mPresenter.addOrderReview(content, image, order_id, rating);
                break;
            case R.id.rl_message:
                Information info = SobotManager.getBaseInfo();
                //SobotApi.setChatTitleDisplayMode(mContext, SobotChatTitleDisplayMode.ShowFixedText, "添加评价");
                SobotApi.setChatTitleDisplayMode(mContext, SobotChatTitleDisplayMode.Default, "");
                if (!TextUtils.isEmpty(order_id)) {
                    info.setSummaryParams(order_id);
                    Map<String, String> customInfo = new HashMap<String, String>();
                    customInfo.put("order_no", order_id);
                    info.setCustomInfo(customInfo);
                }
                SobotApi.startSobotChat(CommentActivity.this, info);
//                CustomerService.getInstance(mContext).connectService("添加评价", null, Config.CUSTOMER);
                break;
        }
    }

    List<File> imageFileList;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            if (data != null && requestCode == IMAGE_PICKER) {//相册
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                uploadImg(images);
            } else if (data != null && requestCode == REQUEST_CODE_SELECT) {//拍照
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                uploadImg(images);
            }
        }
    }

    private void uploadImg(ArrayList<ImageItem> images) {
        List<File> files = new ArrayList<>();
        for (ImageItem item : images) {
            File imgFile = new File(item.path);
            files.add(imgFile);
        }
        if (files.size() > 0 && productList != null) {
            imageFileList = null;
            imageFileList = productList.get(mPosition).getFiles();
            if (imageFileList == null) {
                imageFileList = new ArrayList<>();
                productList.get(mPosition).setFiles(imageFileList);
            }
            //压缩并更新视图,上传图片
            Observable.fromIterable(files).map(new Function<File, File>() {
                @Override
                public File apply(@NonNull File file) throws Exception {
                    if (file != null) {
                        return Luban.with(mContext).load(file).get();
                    }
                    return null;
                }
            }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<File>() {
                @Override
                public void accept(@NonNull File file) throws Exception {
                    if (file != null) {
                        imageFileList.add(file);
                        GridLayout gridLayout = (GridLayout) adapter.getViewByPosition(mPosition, R.id.gridLayout);
                        RelativeLayout rlAddImg = (RelativeLayout) adapter.getViewByPosition(mPosition, R.id.rl_add_img);
                        TextView tvLeft = (TextView) adapter.getViewByPosition(mPosition, R.id.tv_left);

                        if (IMAGE_SIZE <= imageFileList.size()) {
                            rlAddImg.setVisibility(View.GONE);
                        }
                        View imageItem = View.inflate(mContext, R.layout.item_img, null);
                        ImageView imageView = (ImageView) imageItem.findViewById(R.id.image);
                        ImageView iv_delete = (ImageView) imageItem.findViewById(R.id.iv_delete);
                        iv_delete.setTag(mPosition + "_" + imageFileList.size());
                        iv_delete.setOnClickListener(v -> {
                            gridLayout.removeView(imageItem);
                            List<File> fileList = productList.get(mPosition).getFiles();
                            fileList.remove(file);
                            productList.get(mPosition).setFiles(fileList);
                            if (IMAGE_SIZE > fileList.size()) {
                                rlAddImg.setVisibility(View.VISIBLE);
                            }
                            removeImage(mPosition + "_" + imageFileList.size());
                            tvLeft.setText(imageFileList.size() + "/" + IMAGE_SIZE);
                        });

                        productList.get(mPosition).setFiles(imageFileList);
                        tvLeft.setText(imageFileList.size() + "/" + IMAGE_SIZE);

                        gridLayout.addView(imageItem, gridLayout.getChildCount() - 1);
                        App.picasso.load(file).fit().into(imageView);
                        mPresenter.uploadImage(file, "review ", mPosition);
                    }
                }
            });
        }
    }


    private void removeImage(String position) {
        String[] positions = position.split("_");
        int position_1 = 0;
        int position_2 = 0;
        if (positions.length == 2) {
            position_1 = Integer.valueOf(positions[0]);
            position_2 = Integer.valueOf(positions[1]);
        }

        CommentProductBean.DataBean.ShProductsBean bean = productList.get(position_1);
        if(bean != null && bean.getImages() != null && position_2 < bean.getImages().size()){
            bean.getImages().remove(position_2);
        }
    }

    @Override
    public void getCommentProducts(CommentProductBean.DataBean dataBean) {
        productList = dataBean.getSh_products();
        adapter.setNewData(dataBean.getSh_products());
    }

    /**
     * 图片上传成功后的回调
     *
     * @param dataBean
     * @param positon
     */
    @Override
    public void onUploadSuccess(UploadImgBean.DataBean dataBean, int positon) {
        List<UploadImgBean.DataBean> images = productList.get(positon).getImages();
        if (images == null) {
            images = new ArrayList<>();
            productList.get(positon).setImages(images);
        }
        images.add(dataBean);
    }

    @Override
    public void success() {
        tvLogist.setClickable(true);
        Intent broadcast = new Intent();
        broadcast.setAction("refreshUnComemtedFagment");
        mContext.sendBroadcast(broadcast);
        showToast("提交评价成功");
        finish();
    }

    @Override
    public void failed(String msg) {
        tvLogist.setClickable(true);
        showToast(msg);
    }

}
